import React,{ Component } from 'react';
import { Button,Input,List } from 'antd';
// 引入store
import store from './store';


export default class TodoList extends Component{
    constructor(){
        super();
        // getState获取store中的状态
        this.state = store.getState();
        // subscribe 订阅
        // 订阅store ，一旦store 状态数据有更新，会进行触发
        store.subscribe(this.storeChange.bind(this));

    }
    
    // store变化时，修改react state的函数
    storeChange(){
        this.setState(store.getState());
    }
    
    // 输入框变化
    handleChange(e){
        // this.setState({
        //     inputVal: e.target.value
        // });
        // 触发reducer(store)修改数据
        const action = {
            // type必传
            type: 'change_inputVal',
            value: e.target.value
        };
        //dispatch 事件派发
        store.dispatch(action);
    }
    
    // 新增
    handleClick(){
        const action = {
            type: 'add_to_data'
        }
        store.dispatch(action);
    }
    
    //双击删除
    handleDoubleClick(index){
        store.dispatch({
            type: 'del_to_data',
            value: index
        })
    }

    render(){
        return (
            <div style={{padding: '40px'}}>
                <Input 
                placeholder="请输入待办事项" 
                style={{ width: '350px',marginRight: '20px' }}
                value={this.state.inputVal}
                onChange={this.handleChange.bind(this)} 
                />
                <Button 
                type="primary" 
                onClick={this.handleClick.bind(this)}>
                    添加
                </Button>
                <List
                bordered
                style={{ marginTop: '30px',width: '435px',userSelect: 'none' }}
                dataSource={this.state.data}
                renderItem={(item,index) => (
                    <List.Item onDoubleClick={this.handleDoubleClick.bind(this,index)}>{item}</List.Item>
                )}
                />
            </div>
        )
    }
}